package itext.test.example.finalItext;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.itextpdf.text.pdf.parser.ImageRenderInfo;
import com.itextpdf.text.pdf.parser.RenderListener;
import com.itextpdf.text.pdf.parser.TextRenderInfo;

public class PositionRenderListener implements RenderListener {

	private List<String> findText;
	
	// 出现无法取到值的情况，默认为12
	private float defaultH; 
	
	// 可能出现无法完全覆盖的情况，提供修正的参数，默认为2
	private float fixHeight; 

	//将获取到的指定文本的位置信息，存放在map中
	private Map<String, ReplaceRegion> result = new HashMap<String, ReplaceRegion>();

	public PositionRenderListener(List<String> findText, float defaultH, float fixHeight) {
		this.findText = findText;
		this.defaultH = defaultH;
		this.fixHeight = fixHeight;
	}

	public PositionRenderListener(List<String> findText) {
		this.findText = findText;
		this.defaultH = 12;
		this.fixHeight = 2;
	}

	@Override
	public void beginTextBlock() {

	}

	//关键函数，通过api中的函数，获取被替换的文本信息位置
	@Override
	public void renderText(TextRenderInfo textInfo) {
		
		String text = textInfo.getText();
		
		System.out.println(text);
		
		for (String keyWord : findText) {
			if (null != text && text.equals(keyWord)){
				//获取需要改变文字的绝对位置
				com.itextpdf.awt.geom.Rectangle2D.Float bound = textInfo.getBaseline().getBoundingRectange();
				ReplaceRegion region = new ReplaceRegion(keyWord);
				region.setH(bound.height == 0 ? defaultH : bound.height);
				region.setW(bound.width);
				region.setX(bound.x);
				region.setY(bound.y-this.fixHeight);
				result.put(keyWord, region);
			}
		}
	}

	@Override
	public void endTextBlock() {
	}

	@Override
	public void renderImage(ImageRenderInfo renderInfo) {
	}

	public Map<String, ReplaceRegion> getResult() {
		for (String key : findText) {	//补充没有找到的数据
			if(this.result.get(key) == null){
				this.result.put(key, null);
			}
		}
		return this.result;
	}
}
